package com.study.intercept;

import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.study.util.ThreadUtils;

/**
 * @description ExceptionInterceptor 
 * @author TDW
 * @date 2017年6月22日
 *
 */
public class ExceptionInterceptor implements Interceptor {

	//log
	public void intercept(Invocation ai) {
		
		try {
			ai.invoke();
		} catch (final Exception e) {
			//log.error("token 已经超时 !!!!!");
	        ThreadUtils.invoke(new Runnable() {
				public void run() {
					StringBuffer buffer = new StringBuffer();
					buffer.append("<b>"+e.getClass().getName()+": ");
					buffer.append(e.getMessage());
					buffer.append("</b>");
					buffer.append("<br>");
			        StackTraceElement[] trace = e.getStackTrace();
			        if(trace != null && trace.length>0)
			        for (StackTraceElement s : trace) {
			        	buffer.append("&nbsp;&nbsp;&nbsp;&nbsp;at ").append( s ).append("<br>");
			        }
			        System.out.println(buffer.toString());
					//EmailSender.sendSystemException(buffer.toString());
				}
			});
			 
			//log.error("系统异常", e);
			Writer out = null;
			try{
				out = ai.getController().getResponse().getWriter();
			    Map<String,String> json = new HashMap<String,String>();
			    json.put("ret_code", "9999");
				out.write(json.toString());
			    out.flush();
			}catch(Exception ee){
				//log.error("系统返回异常", ee);
			}finally {
				if( out != null){
					 try {
						out.close();
					} catch (IOException e1) {
						//log.error("流关闭异常", e1);
					}
				}
			}
		}
		
	}

	
	
}